﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;

namespace BL.Membership
{
    public class AuthorizePageAttribute : AuthorizeAttribute
    {
        private IEnumerable<UserPermission> _requieredPermissions = Enumerable.Empty<UserPermission>();
        public AuthorizePageAttribute(params UserPermission[] permissions)
        {
            _requieredPermissions = permissions.ToList();
        }

        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            var currentUser = new OrderDeskMembership().GetCurrentLoggedInUser();
            if (currentUser == null)
                return false;

            if (!currentUser.IsUserAllowed(_requieredPermissions))
                return false;

            return true;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var currentUser = new OrderDeskMembership().GetCurrentLoggedInUser();
            if (currentUser == null)
            {
                filterContext.Result = new RedirectToRouteResult(
                               new RouteValueDictionary 
                        {
                            { "action", "Login" },
                            { "controller", "Account" },
                            { "area", "" }
                        });
            }
            else
                base.HandleUnauthorizedRequest(filterContext);
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var currentUser = new OrderDeskMembership().GetCurrentLoggedInUser();
            if (currentUser == null)
            {
                filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary 
                        {
                            { "action", "Logon" },
                            { "controller", "Account" },
                            { "area", "" },
                            { "returnurl", filterContext.HttpContext.Request.Url.PathAndQuery }
                        });
            }
            else if (!currentUser.IsUserAllowed(_requieredPermissions))
            {
                filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary 
                        {
                            { "action", "Unauthorized" },
                            { "controller", "ErrorHandling" },
                            { "area", "" }
                        });
            }
        }
    }
}
